import dotenv from 'dotenv';

// 加载环境变量
dotenv.config();

/**
 * 应用配置
 */
export const config = {
  // 服务配置
  port: parseInt(process.env.PORT || '3001', 10),
  nodeEnv: process.env.NODE_ENV || 'development',

  // 数据库配置
  database: {
    host: process.env.DB_HOST || 'localhost',
    port: parseInt(process.env.DB_PORT || '27017', 10),
    name: process.env.DB_NAME || 'userPermissionServerDb',
    url: process.env.DB_URL || 'mongodb://localhost:27017/userPermissionServerDb',
  },

  // Session配置
  session: {
    secret: process.env.SESSION_SECRET || 'your-super-secret-session-key',
    maxAge: parseInt(process.env.SESSION_MAX_AGE || '86400000', 10), // 24小时
    key: 'user-center-session',
  },

  // 安全配置
  security: {
    bcryptRounds: parseInt(process.env.BCRYPT_ROUNDS || '12', 10),
  },

  // 日志配置
  log: {
    level: process.env.LOG_LEVEL || 'info',
  },

  // CORS配置
  cors: {
    origin: process.env.CORS_ORIGIN || 'http://localhost:3000',
  },

  // 超级管理员配置
  superAdmin: {
    username: process.env.SUPER_ADMIN_USERNAME || 'superadmin',
    email: process.env.SUPER_ADMIN_EMAIL || 'admin@company.com',
    password: process.env.SUPER_ADMIN_PASSWORD || 'SuperAdmin123!',
    realName: process.env.SUPER_ADMIN_REAL_NAME || '超级管理员',
  },
};

/**
 * 验证必要的环境变量
 */
export function validateConfig(): void {
  const requiredEnvVars = ['DB_URL', 'SESSION_SECRET'];

  const missingVars = requiredEnvVars.filter(varName => !process.env[varName]);
  
  if (missingVars.length > 0) {
    throw new Error(`Missing required environment variables: ${missingVars.join(', ')}`);
  }
}

export default config;
